<?php
declare (strict_types=1);

namespace app\common\model\payment;

use app\common\model\BaseModel;
use app\user\model\user\Account;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsTo;
use think\model\relation\HasOne;

/**
 * 订单模型
 */
class PaymentOrderItem extends BaseModel
{
    use SoftDelete;

    /**
     * 表名
     *
     * @var string
     */
    protected $name = 'payment_order_item';

    // 设置json类型字段
    protected $json = ['ext_data', 'credit'];
    // 设置JSON字段的类型
    protected $jsonType = [
        'ext_data->getway' => 'int'
    ];
    /**
     * 设置自动写入时间
     *
     * @var boolean
     */
    protected $autoWriteTimestamp = true;
    // protected $updateTime         = false;
    // protected $hidden = ['delete_time'];

    /**
     * 定义字段类型
     *
     * @var array
     */
    protected $type = [
        'create_time' => 'integer',
        'expire_time' => 'integer',
        'update_time' => 'integer',
    ];

    public function scopeProType($query, $type = 1)
    {
        $query->where('product_type_id', $type);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(Account::class, 'user_id')->append(['avatar_url']);
    }

    public function orderStatus(): BelongsTo
    {
        return $this->belongsTo(PaymentOrder::class, 'order_no', 'order_no')->bind(['status']);
    }

    public function transactionTime(): HasOne
    {
        return $this->hasOne(Transaction::class, 'order_no', 'order_no')->bind(['payment_time']);
    }

    public function scopeDate($query, $date = '')
    {
        switch ($date) {
            case 'this_year':
                $query->where('update_time', '>', strtotime(date('Y', time()) . '-1-1'));
                break;

            case 'earlier':
                $query->where('update_time', '<', strtotime(date('Y', time()) . '-1-1'));
                break;

            default:
                if ($date) {
                    $query->where('update_time', '>', strtotime(date('Y-m-d', strtotime('-' . $date))));
                }
                break;
        }
    }

    public function couponId(): HasOne
    {
        return $this->hasOne(PaymentOrderCoupon::class, 'order_sub_no', 'order_sub_no')->bind(['coupon_id']);
    }

    /**
     * 主订单
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/11/28
     *
     * @return BelongsTo
     */
    public function main(): BelongsTo
    {
        return $this->belongsTo(PaymentOrder::class, 'order_no', 'order_no')->bind(['status', 'payment_time', 'addrinfo', 'status_text']);
    }

    /**
     * successMain
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 23/07/18
     *
     * @return BelongsTo
     */
    public function successMain(): BelongsTo
    {
        return $this->belongsTo(PaymentOrder::class, 'order_no', 'order_no')->where('status', 'IN', '20,30,40');
    }
}
